package com.ishow.noah.widget.canvas.effects

import android.content.Context
import android.graphics.*
import android.text.TextPaint
import android.util.AttributeSet
import android.view.View
import com.ishow.common.extensions.dp2px
import kotlin.math.min


class SweepGradientView @JvmOverloads constructor(
    context: Context,
    attributes: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attributes, defStyleAttr) {

    private lateinit var sweepGradient: SweepGradient
    private val centerPoint = PointF()
    private var radius: Float = 0F

    private val paint = Paint()
    private val textPaint = TextPaint()

    init {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
        paint.isDither = true
        paint.isAntiAlias = true
        textPaint.color = Color.BLACK
        textPaint.textSize = 14F.dp2px()
        textPaint.textAlign = Paint.Align.CENTER
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        val size = min(w, h)
        radius = size * 0.6F / 2F
        centerPoint.x = w / 2F
        centerPoint.y = h / 2F

        val colors = intArrayOf(Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW)
        sweepGradient = SweepGradient(centerPoint.x, centerPoint.y, colors, null)
        paint.shader = sweepGradient
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawCircle(centerPoint.x, centerPoint.y, radius, paint)
        val fontMetrics = paint.fontMetrics
        val distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
        // top
        var x = centerPoint.x
        var y = centerPoint.y - radius - 30
        canvas.drawText("0.75", x, y, textPaint)
        // right
        x = centerPoint.x + radius + 40
        y = centerPoint.y + distance
        canvas.drawText("0.0", x, y, textPaint)

        // bottom
        x = centerPoint.x
        y = centerPoint.y + radius + distance + 40
        canvas.drawText("0.25", x, y, textPaint)

        // left
        x = centerPoint.x - radius - 40
        y = centerPoint.y + distance
        canvas.drawText("0.5", x, y, textPaint)

    }
}